pipeline {
    agent {label 'agent01'}
        // 设置全局选项
    options {
        // 构建超时时间设置为 1 小时
        timeout(time: 1, unit: 'HOURS')
        // 保持最近 10 次构建记录
        buildDiscarder(logRotator(numToKeepStr: '10'))
        // 禁用并发构建
        disableConcurrentBuilds()
    }
    environment {
        BUILD_ARTIFACT = "dist"
        DEPLOY_PATH = "/tmp/web"
        // 不传则使用默认值
        TARGET_HOST = "${params.host ?: 'web'}"
    }
    stages {
        stage('Checkout') {
            steps {
                git url: 'https://gitee.com/LingJianCode/gin-vue3-admin-web.git', branch: 'master'
            }
        }

        stage('Build with Docker') {
            steps {
                script {
                    docker.image('docker.1ms.run/node:20').inside {
                            sh '''
                            npm install pnpm -g
                            pnpm config set registry https://registry.npmmirror.com
                            pnpm install
                            pnpm run build
                            '''
                        }
                }
            }
        }
        stage('Ansible playbook'){
            steps {
                // 多加斜杠，不然会将目录复制进目标路径下
                ansiblePlaybook extras: '-e "host=${TARGET_HOST} remote_path=${DEPLOY_PATH}/ local_path=${WORKSPACE}/${BUILD_ARTIFACT}/"', inventory: '/etc/ansible/hosts', playbook: '/var/jenkins/playbook/gin-vue3-admin-web.yaml'
            }
        }
    }
}